import axios from 'axios'
import vue from 'vue'
import { saveAs } from 'file-saver'

axios.interceptors.request.use(config => {
  config.baseURL = vue.prototype.globalVariable.baseURL
  const tokenName = vue.prototype.globalVariable.tokenName
  // TODO 对是否有token需要 进行验证
  if (window.sessionStorage.getItem(tokenName)) {
    config.headers[tokenName] = window.sessionStorage.getItem(tokenName)
  }
  // 必须加 return config
  return config
})

// TODO 下载功能后期再做
axios.interceptors.response.use(res => {
  const headers = res.headers
  let reg = RegExp(/application\/octet-stream/)
  if (headers['content-type'].match(reg)) {
    console.log('进入下载区');
    let fileName = headers['content-disposition'].split(';')[1].split('filename=')[1]
    fileName = decodeURIComponent(fileName)
    saveAs(new Blob([res.data], { type: 'application/octet-stream' }), fileName)
    res.data = { code: 200, message: "成功" }
    return res
  }
  return res
}, error => {
  return Promise.reject({ code: 410, message: "出现错误" })
})

const request = function (loadtip, query) {
  let loading
  if (loadtip) {
    loading = vue.prototype.$loading({
      lock: false,
      text: '正在加载中…',
      spinner: 'el-icon-loading',
      background: 'rgba(0, 0, 0, 0.5)'
    })
  }
  return axios.request(query)
    .then(res => {
      if (loadtip) {
        loading.close()
      }
      console.log('data', res.data)
      // TODO 返回码需要从resCode中获取
      if (res.data.code === 401) {
        window.sessionStorage.clear()
        vue.prototype.$$router.push({ path: '/login' })
        return Promise.reject(res.data)
      } else if (res.data.code === 500) {
        return Promise.reject(res.data)
      } else if (res.data.code === 502) {
        window.sessionStorage.clear()
        vue.prototype.$$router.push({ path: '/login' })
        return Promise.reject(res.data)
      } else {
        return Promise.resolve(res.data)
      }
    })
    .catch(e => {
      if (loadtip) {
        loading.close()
      }
      vue.prototype.$message.error(e.message)
      return Promise.reject(e.message)
    })
}

const post = function (url, params) {
  const query = {
    url: url,
    method: 'post',
    withCredentials: true,
    timeout: 30000,
    data: params,
    headers: { 'Content-Type': 'application/json', 'request-ajax': true }
  }
  return request(false, query)
}

const postWithLoadTip = function (url, params) {
  const query = {
    url: url,
    method: 'post',
    withCredentials: true,
    timeout: 30000,
    data: params,
    headers: { 'Content-Type': 'application/json', 'request-ajax': true }
  }
  return request(true, query)
}

const postWithOutLoadTip = function (url, params) {
  const query = {
    url: url,
    method: 'post',
    withCredentials: true,
    timeout: 30000,
    data: params,
    headers: { 'Content-Type': 'application/json', 'request-ajax': true }
  }
  return request(false, query)
}

const get = function (url, params) {
  const query = {
    url: url,
    method: 'get',
    withCredentials: true,
    timeout: 30000,
    params: params,
    headers: { 'request-ajax': true }
  }
  return request(false, query)
}

const form = function (url, params) {
  const query = {
    url: url,
    method: 'post',
    withCredentials: true,
    timeout: 30000,
    data: params,
    headers: { 'Content-Type': 'multipart/form-data', 'request-ajax': true }
  }
  return request(false, query)
}

const userExcelUpdate = function (url, params) {
  const query = {
    url: url,
    method: 'post',
    withCredentials: true,
    timeout: 30000,
    data: params,
    responseType: 'blob',
    headers: { 'Content-Type': 'multipart/form-data', 'request-ajax': true }
  }
  return request(false, query)
}

export {
  post,
  postWithLoadTip,
  postWithOutLoadTip,
  get,
  form,
  userExcelUpdate
}
